from django.shortcuts import render
from django.http import JsonResponse
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from app.models import datas, trace
import json
from threading import Thread
import socket
import sys;

sys.path.append("./app")
from car.carServer import CarServer
from distutils.util import strtobool

# Create your views here.

carserver = CarServer()
thread = Thread(target=carserver.run_server)
thread.setDaemon(True)
thread.start()


class CarView():

    def car_move(request):
        response = {}
        if request.method == 'GET':
            direction = request.GET.get("direction")  # 获取运动元组
            carIP = request.GET.get("carIP")  # 获取控制的小车的ip
            direction = direction.split(',')
            for _ in range(4):
                direction[_] = strtobool(direction[_])

            if carIP in carserver.client_connect_pool.keys():  # 该小车的ip已经连接基站
                content = {}
                content["direction"] = direction
                package = carserver.__generate_package__(content, 2, 0, carIP)
                # print(package)
                carserver.__sending_package__(package, carIP)

            return JsonResponse(response)

    def car_sensor(request):
        response = {}
        if request.method == 'GET':
            # carIP =request.GET.get("car")#        获取需要获取数据的小车的ip
            pageNum = request.GET.get('pageNum')
            pageSize = int(request.GET.get('pageSize'))

            book_list = datas.objects.all()
            paginator = Paginator(book_list, pageSize)
            response['total'] = paginator.count
            try:
                books = paginator.page(pageNum)
            except PageNotAnInteger:
                books = paginator.page(1)
            except EmptyPage:
                books = paginator.page(paginator.num_pages)
            response['list'] = json.loads(serializers.serialize("json", books))
            # book_list = datas.objects.all().extra(tables=['datas'],where=['id > 52'])
            # response['list'] = json.loads(serializers.serialize("json", book_list))
            return JsonResponse(response)
        return JsonResponse(response)

    def trace_max_id(request):
        response = {}
        if request.method == 'GET':
            carIP = request.GET.get("carIP")
            s = 'select max(id) from trace where pi=\'' + carIP + '\''
            id_map = {'max(id)': 'id'}
            max_id = trace.objects.raw(s, translations=id_map)
            response['max_id'] = max_id[0].id
            return JsonResponse(response)

    def trace_record(request):
        response = {}
        if request.method == 'GET':
            carIP = request.GET.get("carIP")
            max_id = request.GET.get("max_id")
            s = 'select * from trace where pi = \'' + carIP + '\'' + 'and id > ' + max_id
            # print(s)
            trace_map = {'id': 'id', 'x': 'x', 'y': 'y', 'pi': 'pi'}
            trace_all = trace.objects.raw(s, translations=trace_map)
            response['trace_list'] = []
            for _ in range(len(trace_all)):
                t = {}
                t['id'] = trace_all[_].id
                t['x'] = trace_all[_].x
                t['y'] = trace_all[_].y
                t['pi'] = trace_all[_].pi
                # print(trace_all[_].id)
                # print(type(trace_all[_].id))
                response['trace_list'].append(t)

            return JsonResponse(response)


